<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="63px"
        formItemWidth="auto"
        :model="searchParam"
      >
        <template #after>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          @click="
            useDownload('/mes/mesworkorderplan/export', '生产计划', searchParam)
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>
      <!-- 表格主体 -->
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        v-bind="$attrs"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->

        <!-- 表格内容操作 -->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>

        <!-- <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <add-table
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="reset"
      @change-visible="changeVisible"
    />

    <!-- 列设置 抽屉组件 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import { filterOrder } from "@/utils/commonHooks";
import {
  getPlantList,
  getWorkShopList,
  getMaterials,
} from "@/utils/commonData";
import { getMesprocessList } from "@/api/andon/andon";
import request from "@/utils/request";
defineOptions({
  name: "STATISTICALQUERYPRODUCEPLAN",
  inheritAttrs: false,
});

/** 自定义设置方法   start **/

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "select",
    label: "工厂",
    isShow: true,
    fieldName: "plantId",
    placeholder: "请选择工厂",
    initValue: null,
    defaultFirstOption: true,

    optionList: [],
    change: (e) => {
      selectPlant(e);
    },
  },
  {
    type: "select",
    label: "工作中心",
    isShow: true,
    fieldName: "workCenterIds",
    placeholder: "请选择工作中心",
    initValue: null,
    defaultFirstOption: true,
    multiple: true,
    collapseTags: true,
    style: "width: 300px !important",
    fitInputWidth: true,
    change: (e) => {
      selectWorkCenter(e);
    },
  },
  {
    type: "input",
    label: "存货编码",
    isShow: true,
    fieldName: "materialCode",
    placeholder: "请选择存货编码",
    initValue: "",
  },
  {
    type: "select",
    label: "班次",
    isShow: true,
    fieldName: "shiftId",
    placeholder: "请选择班次",
    initValue: null,
    defaultFirstOption: true,
    optionList: [],
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "批次号", // 标签文本
    fieldName: "planBatch", // 字段名称
    placeholder: "请输入批次号", // 提示文字
    initValue: "", // 默认值
  },

  {
    type: "date", // 普通输入框
    isShow: true,
    valueFormat: "YYYY-MM-DD",
    dataType: "daterange", // 类型, text/textarea
    label: "生产时间", // 标签文本
    fieldName: "planDateSearch", // 字段名称
    startPlaceholder: "开始日期", // 提示文字
    endPlaceholder: "结束日期", // 提示文字
    initValue: "", // 默认值
    rangeSeparator: "至",
    change: (e: any) => getRequestTime(e),
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "plantCode",
    label: "工厂",
    isShow: true,
    width: 100,
    align: "left",
    render: (scope: any) => <span>{scope.row?.plantCode ?? ""}</span>,
  },
  {
    prop: "workCenterCode",
    label: "工作中心",
    isShow: true,
    minWidth: 180,
    align: "left",
    render: (scope: any) => (
      <span>{`${scope.row.workCenterCode ?? ""}-${
        scope.row.workCenterName ?? ""
      }`}</span>
    ),
  },
  {
    prop: "materialCode",
    label: "存货编码-名称",
    isShow: true,
    minWidth: 180,
    align: "left",
    render: (scope: any) => (
      <span>{`${scope.row.materialCode ?? ""}-${
        scope.row.materialName ?? ""
      }`}</span>
    ),
  },
  {
    prop: "planBatch",
    label: "批次号",
    minWidth: 120,
    isShow: true,
    align: "left",
  },
  {
    prop: "shiftName",
    label: "班次",
    minWidth: 150,
    isShow: true,
    align: "left",
    render: (scope: any) => (
      <span>{`${scope.row.shiftCode ?? ""}-${scope.row.shiftName ?? ""}`}</span>
    ),
  },

  {
    prop: "planQuantity",
    label: "计划数量",
    minWidth: 100,
    headerAlign: "center",
    align: "right",
    isShow: true,
  },
  {
    prop: "planFinishQuantity",
    label: "完成数量",
    minWidth: 100,
    headerAlign: "center",
    align: "right",
    isShow: true,
  },
  {
    prop: "quantityUnit",
    label: "数量单位",
    minWidth: 100,
    isShow: true,
    align: "left",
    render: (scope: any) => (
      <span>{useDictionary("MeasurementUnit", scope.row.quantityUnit)}</span>
    ),
  },
  {
    prop: "planDate",
    label: "日期",
    minWidth: 150,
    isShow: true,
    render: (scope: any) => <span>{scope.row.planDate?.split(" ")[0]}</span>,
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

/** 列表项自定义方法   end **/

// 请求参数
const requestApi = "/mes/mesworkorderplan/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({ sort: {} });

// 初始化搜索参数数据
const searchParamInit = {};

const deleteParam = {
  api: "/system/sysRole/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
onMounted(async () => {
  getTableList();
  getSelectPlantList();
});

// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

// 获取工厂列表
async function getSelectPlantList() {
  const list = (await getPlantList()) ?? [];
  list?.map((item) => {
    item.label = `${item.organizationCode}`;
    item.value = `${item.id}`;
  });
  searchColumns[0].optionList = list;
  searchParam.value.plantId = list[0].id;
  selectPlant(searchParam.value.plantId);
}

// 工厂选择
async function selectPlant(e: string) {
  if (e) {
    // 获取工作中心列表
    const list = (await getWorkShopList(e)) ?? [];
    list?.map((item) => {
      item.label = `${item.workshopCode}-${item.workshopName}`;
      item.value = `${item.id}`;
    });
    searchColumns[1].optionList = list;
    searchParam.value.workCenterId = "";
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
    // searchColumns[3].optionList = [];
    // searchParam.value.shiftId = "";
    getDateshiftCountList();
  } else {
    searchColumns[1].optionList = [];
    searchParam.value.workCenterId = "";
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
    // searchColumns[3].optionList = [];
    // searchParam.value.shiftId = "";
  }
}

// 工作中心选择
function selectWorkCenter(e: any) {
  searchColumns[2].optionList = [];
  searchParam.value.materialId = "";
  if (e) {
    // getMaterialList();
  } else {
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
    // searchColumns[3].optionList = [];
    // searchParam.value.shiftId = "";
  }
}

// 加工时间选择
function getRequestTime(data: any) {
  if (data) {
    searchParam.value.planDateStart = data[0];
    searchParam.value.planDateEnd = data[1];
  } else {
    searchParam.value.planDateStart = "";
    searchParam.value.planDateEnd = "";
  }
}

// 物料列表获取
async function getMaterialList() {
  const list = await getMaterials(
    searchParam.value.plantId,
    searchParam.value.workCenterId
  );
  list?.forEach((item) => {
    item.label = `${item.materialCode}-${item.materialName}`;
    item.value = `${item.id}`;
  });
  searchColumns[2].optionList = list;
}
// 班次获取
async function getDateshiftCountList() {
  let list = "";
  await request({
    url: `/mes/messhift/getList`,
    method: "post",
    data: { enabled: 1, plantId: searchParam.value.plantId },
  }).then((res) => {
    list = res.data;
  });

  list?.forEach((item) => {
    item.label = `${item.shiftCode}-${item.shiftName}`;
    item.value = `${item.id}`;
  });
  console.log(list);

  searchColumns[3].optionList = list;
}
// 重置数据处理
function handleReset() {
  reset();
  getSelectPlantList();
  searchColumns[1].optionList = [];
  searchColumns[2].optionList = [];
  searchColumns[3].optionList = [];
}

/** 打开角色表单弹窗 */
const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});

const classData = {
  id: "jeffjeffjeffjeffjeffjeff",
  className: "hahaha",
  classPerson: "asdcasd",
  classTeacher: "jeff",
  classId: "jeffjeff",
  studentData: [
    {
      id: "111",
      sex: "1",
      name: "haha",
      isLive: false,
      phone: "17600002036",
    },
    {
      id: "222",
      sex: "2",
      name: "haha8989",
      isLive: true,
      phone: "17600602036",
    },
  ],
};

function openDialog(roleObj?: Object) {
  addDialog.visible = true;
  if (roleObj) {
    addDialog.title = "修改角色";
    addDialog.data = classData;
    console.log("修改角色", addDialog.data);
  } else {
    addDialog.title = "新增角色";
  }
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
}
</script>
